#include "mainwidget.h"
#include "ui_mainwidget.h"
#include <QDebug>
#include <QKeyEvent>
#include <QMediaPlaylist>
#include <QPainter>
#include <QMediaMetaData>
#include "login.h"
#include "songtable.h"
#include <QScrollBar>
static const char serverHost[] = "https://163.lpddr5.cn/";
static const int serverPort = 3000;
MainWidget::MainWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MainWidget)
{
    this->setMouseTracking(true);
    initUI();
    // auto sw = new LoginWindow();
    // sw->show();
    QFile file("save_musicList");
    if (file.exists()) {
        file.open(QIODevice::ReadOnly);
        QDataStream in(&file);
        SongList songList;
        in >> songList;
        playList->loadList(songList);
        file.close();
    }
    connect(ui->closeButton1, &QPushButton::clicked, this, [=](){this->close(); QApplication::quit();});
    connect(ui->maxButton1, &QPushButton::clicked, this, [=](){this->maxRestore();});
    connect(ui->minButton1, &QPushButton::clicked, this, [=](){this->showMinimized();});
    connect(mw, &MusicWidget::musicClicked, this, [=](){
        this->setGeometry(mw->geometry());
        this->show();
        mw->hide();});
    connect(ui->listButton, &QPushButton::clicked, this, [=](){
        musicList->show();
        musicList->activateWindow();
    });
    // connect(musicList, &MusicList::addSongs, this, &MainWidget::addSongs);
    player->setMedia(playList);
    playList->setCurrentIndex(-1);
    ui->playModeBox->addItem("单曲循环");
    ui->playModeBox->addItem("顺序播放");
    ui->playModeBox->addItem("列表循环");
    ui->playModeBox->addItem("随机播放");
    playMode = PlayList::CurrentItemInLoop;
    playList->setPlaybackMode(PlayList::PlaybackMode::CurrentItemInLoop);
    connect(ui->playModeBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [=](int ind){
        PlayList::PlaybackMode mode[4] = {PlayList::PlaybackMode::CurrentItemInLoop,PlayList::PlaybackMode::Sequential,
                                         PlayList::PlaybackMode::Loop,PlayList::PlaybackMode::Random};
       playList->setPlaybackMode(mode[ind]);
       playMode = mode[ind];
    });
    connect(ui->nextButton, &QPushButton::clicked, playList, [=](){
        if (playList->isEmpty())
            return ;
        playList->setCurrentIndex((playList->currentIndex() + 1) % playList->mediaCount());
        playSlot();
    });
    connect(ui->lastButton, &QPushButton::clicked, playList, [=](){
        if (playList->isEmpty())
            return ;
        int ind = playList->currentIndex() - 1;
        playList->setCurrentIndex(ind < 0 ? playList->mediaCount() - 1 : ind);
        playSlot();
    });

    // connect(playList, &QMediaPlaylist::currentIndexChanged, this, [=](){
        // qDebug() << "current index"<<playList->currentIndex();
        // startPlay();
        // playSlot();
    // });
    connect(network, &Network::searchDone, this, [=](SongList sList){
        sList.wirteToTable(ui->searchTable);
    });
    connect(network, &Network::getPlayListByIdDone, this, [=](SongList sList){
        // int Row = ui->leftList->currentRow();
        auto tb = ui->stackedWidget2->currentWidget()->findChild<QTableWidget*>();
        sList.wirteToTable(tb);
    });
    connect(&network->songUrlProcess, &SongUrlProcess::getSongUrlDone, this, [=](Song song){
        playList->appendAndPlay(song);
    });
    connect(this->ui->playButton, &QPushButton::clicked, this, [=](){
       if (playState == PlayState::playing)
           this->stopSlot();
       else
           this->playSlot();
    });
    connect(player, &QMediaPlayer::stateChanged, this, [=](QMediaPlayer::State state){
        if (state == QMediaPlayer::State::StoppedState)
            this->stopSlot();
    });
    ui->musicSlider->setMinimum(0);
    connect(player, &QMediaPlayer::durationChanged,this, [=](qint64 dt){
        ui->musicSlider->setMaximum((int)dt);
    ui->endTimeLabel->setText(QString("%1:%2").arg(player->duration()/60000, 2, 10, QChar('0')).arg(
                                  player->duration()/1000 % 60,2,10,QChar('0')));
    });
    connect(player, &QMediaPlayer::positionChanged, this,[=](qint64 pos){
       ui->musicSlider->setValue((int)pos);
        ui->lyricDisplay->setPosition(pos);
        ui->curTimeLabel->setText(QString("%1:%2").arg(player->position()/60000, 2, 10, QChar('0')).arg(
                                  player->position()/1000 % 60,2,10,QChar('0')));
    });
    connect(ui->musicSlider, &QAbstractSlider::sliderMoved, player, &QMediaPlayer::setPosition);
    playList->setPlaybackMode(QMediaPlaylist::PlaybackMode::CurrentItemOnce);
    ui->volumeSlider->setMinimum(0);
    ui->volumeSlider->setMaximum(100);
    ui->volumeSlider->setValue(player->volume());
    connect(ui->volumeSlider, &QAbstractSlider::sliderMoved, player, &QMediaPlayer::setVolume);
    connect(network, &Network::getLyricDone, this, [=](QString lyric){
        ui->lyricDisplay->setLyric(lyric);
    });
    //connect(player, &QMediaPlayer::mediaChanged, this, &MainWidget::startPlay);
    auto childList = findChildren<QWidget*>();
    for (int i = 0; i < childList.size(); i++) {
        childList[i]->setMouseTracking(true);
    }
    connect(this->musicList, &MusicList::musicListDoubleClicked, this, &MainWidget::startPlay);
    connect(this->playList, &QMediaPlaylist::currentMediaChanged, this, [=](){
        startPlay(-1);});
    connect(this->playList, &PlayList::wantPlay, this, &MainWidget::playSlot);

}

MainWidget::~MainWidget()
{
    delete ui;
}

void MainWidget::maxRestore()
{
    static bool isMax = false;
    if (isMax) {
        this->showNormal();
        isMax = false;
    } else {
        this->showMaximized();
        isMax = true;
    }
}

void MainWidget::playSlot()
{
    //不处理切换歌曲
    if (playState == PlayState::playing)
        return ;
    if (!playList->isEmpty()) {
        if (playList->currentIndex() == -1)
            playList->setCurrentIndex(0);
        player->play();
    playList->setPlaybackMode(playMode);


    playState = PlayState::playing;


    ui->playButton->setStyleSheet(
R"EOF(QPushButton#playButton{background-color: rgba(0, 0, 0, 0);
border-width: 0px;
border-image:url(":/pic/stop.png");}
QPushButton#playButton:hover{background-color: rgba(0, 0, 0, 0);
border-width: 0px;
border-image:url(":/pic/stop1.png");})EOF"
                );
    }


}
void MainWidget::stopSlot()
{
    if (playState == PlayState::stop)
        return ;
    player->pause();
    playState = PlayState::stop;
    ui->playButton->setStyleSheet(
R"EOF(QPushButton#playButton{background-color: rgba(0, 0, 0, 0);
border-width: 0px;
border-image:url(":/pic/play.png");}
QPushButton#playButton:hover{background-color: rgba(0, 0, 0, 0);
border-width: 0px;
border-image:url(":/pic/play1.png");})EOF"
                );

}

void MainWidget::startPlay(int n)
{
    /*加载歌词
     * 显示时间
     * 显示歌名/歌手
     */

    //如果歌词为空，并且是网络音乐，从网络请求歌词
    //歌词后保存到playList,并加载
    int index = n;
    if (n < 0)
        index = playList->currentIndex();
    Song song = playList->getSongByIndex(index);
    if (!song.lyric.isEmpty()) {
        ui->lyricDisplay->setLyric(song.lyric);
    } else if (!song.url.isLocalFile()) {
        network->getLyric(song.id);
    }
    ui->endTimeLabel->setText(QString("%1:%2").arg(player->duration()/60000, 2, 10, QChar('0')).arg(
                                  player->duration()/1000 % 60,2,10,QChar('0')));
    ui->titleLabel->setText(QString("%1\n%2").arg(song.songName).arg(song.artistName));
    if (n >= 0) {
        playList->setCurrentIndex(n);
        this->playSlot();
    }
}

void MainWidget::paintEvent(QPaintEvent *ev)
{
    //标题栏上色
   Q_UNUSED(ev);
   QPainter p(this);
   p.setPen(Qt::NoPen);
   p.setBrush(QColor(140, 167, 255));
   p.drawRect(this->ui->topwidget->geometry());
   QWidget::paintEvent(ev);
}

void MainWidget::initUI() {
    player = new QMediaPlayer(this);
    ui->setupUi(this);
    ui->endTimeLabel->clear();
    ui->titleLabel->clear();
    ui->curTimeLabel->clear();
    ui->leftList->horizontalScrollBar()->hide();
    // ui->searchTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    // ui->searchTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
   // ui->searchTable->setFrameShape(QFrame::NoFrame);
   // ui->searchTable->setShowGrid(false);
   // ui->searchTable->verticalHeader()->hide();
   // ui->searchTable->setStyleSheet("QHeaderView::item{background-color: rgba(219, 255, 171, 0);color:#663E00;}");
   // ui->searchTable->setEditTriggers(QAbstractItemView::NoEditTriggers);

    this->setWindowFlags(Qt::FramelessWindowHint);
   QFile qSSFile(":/styleSheet.qss");
   qSSFile.open(QIODevice::ReadOnly);
    this->setStyleSheet(qSSFile.readAll());
    qSSFile.close();
    mw = new MusicWidget();
    musicList  = new MusicList();
    playList = musicList->getPlayList();
    QUrl url(serverHost);
   // url.setPort(3000);
    network = new Network(url);
    ui->searchTable->setColumnCount(2);
    ui->searchTable->setHorizontalHeaderLabels({"歌名","歌手"});
    m_login = new login();
   connect(m_login, &login::loginSignal, network, &Network::login);
    connect(m_login, &login::logoutSignal, this, &MainWidget::logoutRequestSlot);
    connect(network, &Network::loginResult, m_login, &login::loginResult);
    connect(network, &Network::loginResult, this, [=](bool state){
        if (state) {
            ui->loginButton->setText(network->nickname);
            network->getPlayList();
        }
    });
    connect(network,&Network::getPlayListDone, this, [=](QList<NetPlayList> playlist){
        for (auto &item : playlist) {
            auto listItem = new QListWidgetItem(ui->leftList);
            listItem->setText(item.name);
            listItem->setData(Qt::UserRole, item.id);
            QWidget *w = new QWidget();
            QHBoxLayout *layout = new QHBoxLayout(w);
            SongTable *tb = new SongTable(w);
            layout->addWidget(tb);
            // tb->setHorizontalHeaderLabels({"歌名","歌手"});
            w->setLayout(layout);
            ui->stackedWidget2->addWidget(w);
            connect(tb, &SongTable::cellClicked, this, [=](int row, int col){
                Q_UNUSED(col)

                unsigned int id = tb->item(row, 0)->data(Qt::UserRole).toUInt();
                QString title = tb->item(row, 0)->text();
                QString name = tb->item(row, 1)->text();
                network->getSongUrl(Song(title, name, QUrl(), id));

            });
        }
    });

    // ui->leftList->addItem("本地音乐");
    ui->leftList->addItem("搜索页");
    connect(ui->leftList, &QListWidget::currentRowChanged, this, [=](int row){
        ui->stackedWidget2->setCurrentIndex(row);
        if (row > 0) {
            auto id = ui->leftList->item(row)->data(Qt::UserRole).toUInt();
            network->getPlayListById(id);
        }
    });


}

namespace{
enum ResizeType {
FromRight,
FromBottom,
FromRightBottom,
None
};
ResizeType resizeType;
const int marginSize = 5;
QRect originRect;
int originX;
int originY;
}
void MainWidget::mousePressEvent(QMouseEvent *event)
{
    musicList->hide();
    if (event->x() >= width()-marginSize && event->y() >= height() - marginSize) {
        resizeType = FromRightBottom;
        originRect = geometry();
        originX = event->globalX();
        originY = event->globalY();
    } else if (event->x() >= width() - marginSize) {
        resizeType = FromRight;
        originRect = geometry();
        originX = event->globalX();
        originY = event->globalY();

    } else if (event->y() >= height()- marginSize) {
        resizeType = FromBottom;
        originRect = geometry();
        originX = event->globalX();
        originY = event->globalY();
    } else {
        resizeType = None;
    }
    if (event->button() == Qt::LeftButton && event->y() < 100) {
       movePoint = event->globalPos() - this->pos();
    }
}

void MainWidget::mouseMoveEvent(QMouseEvent *event)
{
    if (event->x() >= width() - marginSize && event->y() >= height() - marginSize) {
        auto tmpCursor = cursor();
        tmpCursor.setShape(Qt::CursorShape::SizeFDiagCursor);
        setCursor(tmpCursor);
    } else if (event->x() >= width() - marginSize) {
        auto tmpCursor = cursor();
        tmpCursor.setShape(Qt::CursorShape::SizeHorCursor);
        setCursor(tmpCursor);
    } else if (event->y() >= height()- marginSize) {
        auto tmpCursor = cursor();
        tmpCursor.setShape(Qt::CursorShape::SizeVerCursor);
        setCursor(tmpCursor);
    } else {
        auto t = cursor();
        t.setShape(Qt::CursorShape::ArrowCursor);
        setCursor(t);
    }
    if (event->buttons() == Qt::LeftButton ) {
        if (resizeType == FromRight) {
            setGeometry(geometry().x(), geometry().y(), originRect.width() + event->globalX() - originX,
                        geometry().height());
            return ;
        } else if (resizeType == FromBottom) {
            setGeometry(geometry().x(), geometry().y(), originRect.width(), originRect.height() + event->globalY() - originY);
            return ;
        } else if (resizeType == FromRightBottom) {
            setGeometry(geometry().x(), geometry().y(), originRect.width() + event->globalX() - originX, originRect.height() + event->globalY() - originY);
            return ;
        }
    }
    if (event->buttons() == Qt::LeftButton && event->y() < 100)
        this->move(event->globalPos() - movePoint);
}

void MainWidget::closeEvent(QCloseEvent *ev)
{
    Q_UNUSED(ev);
    playList->saveInFile("save_musicList");
}

void MainWidget::resizeEvent(QResizeEvent *ev)
{
    ui->widget->move(ui->bottomwidget->width() / 2 - ui->widget->width() / 2,0);
    ui->widget_2->move(ui->bottomwidget->width() - ui->widget_2->width() - 5, 0);
}


void MainWidget::on_musicButton_clicked()
{
    if (ui->topStackedWidget->currentIndex() == 0) {
        ui->topStackedWidget->setCurrentIndex(1);
    } else {
        ui->topStackedWidget->setCurrentIndex(0);
    }
}

// void MainWidget::addSongs(QList<QUrl> *urls) {
    // for (int i = 0; i < urls->size(); i++) {
        // playList->addMedia((*urls)[i]);
    // }
    // player->play();

// }

void MainWidget::on_searchEdit_returnPressed()
{
    network->search(ui->searchEdit->text());
    ui->leftList->setCurrentRow(1);
    ui->topStackedWidget->setCurrentIndex(0);
}


// void MainWidget::on_searchTable_itemDoubleClicked(QTableWidgetItem *item)
// {
    // unsigned int id = item->data(Qt::UserRole).toUInt();
    // network->getSongUrl(Song("xxx", "xxx", QUrl(), id));
// }


void MainWidget::on_searchTable_cellDoubleClicked(int row, int column)
{
    Q_UNUSED(column);
    unsigned int id = ui->searchTable->item(row, 0)->data(Qt::UserRole).toUInt();
    QString title = ui->searchTable->item(row, 0)->text();
    QString name = ui->searchTable->item(row, 1)->text();
    network->getSongUrl(Song(title, name, QUrl(), id));
//    network->getLyric(id);

}

void MainWidget::logoutRequestSlot()
{
    ui->loginButton->setText("登录");
    ui->leftList->setCurrentRow(0);
    while(ui->leftList->count() > 1) {
        delete ui->leftList->item(1);
    }
    ui->stackedWidget2->setCurrentIndex(0);
     while(ui->stackedWidget2->count() > 1) {
        delete ui->stackedWidget2->widget(1);
     }
     network->logout();
}





void MainWidget::on_loginButton_clicked()
{
    m_login->show();
}

